package com.xc.hotelmgr.order.modules.yd.sdk;

import cn.hutool.http.HttpUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class YdReq {

    private static Logger logger = LoggerFactory.getLogger(YdReq.class);
    private static String SING_KEY = "71852a27d339";

    private static String genSign(Map<String, String> paramMap) {
        if (MapUtils.isEmpty(paramMap)) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        paramMap.remove("sign");

        Map < String, String > treeMap = new TreeMap< String, String >(paramMap);
        Iterator< String > iter = treeMap.keySet().iterator();
        while (iter.hasNext()) {
            String name = (String) iter.next();
            if (StringUtils.isBlank(ObjectUtils.toString(treeMap.get(name)))) {
                continue;
            }
            sb.append(name).append(treeMap.get(name));
        }
        logger.info("签名源字符串:" + sb.toString() + SING_KEY);
        return DigestUtils.md5Hex((sb.toString()+SING_KEY).getBytes());
    }

    public static String req(String url, Map map){
        String sign = genSign(map);
        map.put("sign",sign);
        return HttpUtil.post(url,map);
    }
}
